package com.nsoft.ui;

import com.nsoft.utils.BookArrayAdapter;
import com.nsoft.utils.Constant;
import com.nsoft.utils.engine;
import com.nsoft.utils.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;

public class BookListFragment extends ListFragment {
    public interface OnBookSelectListener{
    	public void onBookSelected(int idx);
    }

    Context context;
	OnBookSelectListener bookSelectListener;
    ProgressDialog pd;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	
    	context=getActivity();
    	startUp(context);
    }
    
    @Override
    public void onStart() {
    	super.onStart();
    	
    	/*
    	if (getFragmentManager().findFragmentById(
    			R.id.booklist_fragment)!=null){
    		getListView().setChoiceMode(
    				ListView.CHOICE_MODE_SINGLE);
    	}
    	*/
    }
    
   
    @Override
    public void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);

    }
    
    
    
    @Override
    public void onAttach(Activity activity) {
    	super.onAttach(activity);
    	try{
    		bookSelectListener=
    				(OnBookSelectListener)activity;
    	}catch(ClassCastException cce){
    		throw new ClassCastException(
    			Constant.booklist.
    			BLF_SELECT_LISTENER_NOT_IMPLEMENTED.
    			replace(Constant.CHR_REPLACE,
    					activity.toString()));
    	}
    }
    
    @Override
    public void onListItemClick(ListView l, 
    		View v, int position, long id) {
    	bookSelectListener.onBookSelected(position);
    	getListView().setItemChecked(position,true);
    }
    
    private void startUp(Context ctx){
    	int syncSrc=SyncBookThread.SYNC_SOURCE_HISTORY;
    	getBookList(ctx,syncSrc);
    	
    	FragmentActivity actor=(FragmentActivity)ctx;
    	ImageButton refreshBtn=(ImageButton)actor.
    			findViewById(R.id.refreshButton);
    	refreshBtn.setOnClickListener(
    			new SyncWithServer(actor));
    	

    }
    

    private void getBookList(Context ctx,int syncSrc){
    	engine.setEngineServer("http://112.216.110.218:8090/dms/");
    	engine.setEngineParams("linkageproject.htm?language=1");

		pd=ProgressDialog.show(ctx,
				Constant.booklist.BLF_SERVER_UPDATE,
				syncSrc==SyncBookThread.SYNC_SOURCE_SERVER? 
					Constant.booklist.BLF_SERVER_SYNCHRONIZE:
					Constant.booklist.BLF_BOOKLIST_SYNCHRONIZE,
				true,false);
	
		new SyncBookThread(ctx,syncSrc).start();
    }
    
    private class SyncWithServer 
    		implements View.OnClickListener{
    	private Context context;
    	
    	public SyncWithServer(Context ctx){
    		this.context=ctx;
    	}
    	
		@Override
		public void onClick(View v) {
			AlertDialog.Builder alert=
					new AlertDialog.Builder(
							this.context);
				alert.setIcon(R.drawable.ic_help);
				alert.setTitle(Constant.DIALOG_CONFIRM).
					setMessage(Constant.
							booklist.BLF_SERVER_SYNC_CONFIRM).
					setPositiveButton(Constant.DIALOG_YES,
						new DialogInterface.OnClickListener(){
							@Override
							public void onClick(
									DialogInterface arg0, 
									int arg1){
								getBookList(context,
									SyncBookThread.
										SYNC_SOURCE_SERVER);
							}
						
					}).setNegativeButton(Constant.DIALOG_NO,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(
									DialogInterface dialog,
									int which){
								dialog.cancel();
							}
					}).create().show();
			
		}
    	
    }
    
    /**
     * this class is for synchronizing with server/local 
     * history. and return the handle back to the UI
     * 
     * @author m_
     */
    private class SyncBookThread extends Thread{
    	public static final int SYNC_SOURCE_HISTORY=1;
    	public static final int SYNC_SOURCE_SERVER=0;
    	
    	public static final int SYNC_SERVER_FAILED=1;
    	public static final int SYNC_LOCAL_FAILED=2;
    	public static final int SYNC_COMPLETED=0;
    	
    	Context context;
    	int syncSource=SYNC_SOURCE_HISTORY;
    	int syncRes=SYNC_COMPLETED;
    	
    	public SyncBookThread(Context _ctx,int syncSrc){
    		this.context=_ctx;
    		this.syncSource=syncSrc;
    	}
    	
    	public void run(){
    		if (syncSource==SYNC_SOURCE_SERVER){
    			try{
    				engine.getBookListFromServer();
    			}catch(Exception e){
    				Log.v("SyncBookThread<-Server",
           				e.getClass()+": "+e.getMessage());
    				syncRes=SYNC_SERVER_FAILED;
    			}
    		}else if (syncSource==SYNC_SOURCE_HISTORY){
    			try{
    				engine.getBookListFromHistory();
    			}catch(Exception e){
    				Log.v("SyncBookThread<-HistoryList",
           				e.getClass()+": "+e.getMessage());
    				syncRes=SYNC_LOCAL_FAILED;
    			}
    		}
    		engine.getBookThumbBitmapsFromHistory();
    		handler.sendEmptyMessage(0);
    	}
    	
    	@SuppressLint({ "HandlerLeak" })
    	private Handler handler=new Handler(){
    		@Override
    		public void handleMessage(android.os.Message msg) {
    			pd.dismiss();
    			
    			if (syncRes==SYNC_SERVER_FAILED){
    				utils.showInfo(context,
						Constant.DIALOG_ALERT,
						Constant.booklist.BLF_LOAD_FROMSERVER_FAILED);
    			}else if (syncRes==SYNC_LOCAL_FAILED){
    				utils.showInfo(context,
    					Constant.DIALOG_ALERT,
    					Constant.booklist.BLF_LOAD_FROMLOCAL_FAILED);
    			}
    			setListAdapter(new BookArrayAdapter(context,
	    					engine.getBookTitles(),
	    					engine.getThumbList()));
    		}
    	};
    }
}
